package com.b2b.util;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.b2b.exception.CustomUnauthorizedException;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.b2b.model.entity.SMS;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.http.HTTPException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SMSUtil {
    public static String sendSMS(HttpServletRequest request, SMS sms) {
        /*
        修改 1109984 code
        登录 1109983 code min
        注册 1109982 code min
         */
        String phoneNumber = sms.getPhone();
        Integer min = sms.getMin();
        String reStr = ""; //定义返回值
        // 短信应用SDK AppID  1400开头
        int appid = 1400568748;
        // 短信应用SDK AppKey
        String appkey = "3fb9f1c81883b765213f46cdb41767cf";
        // 短信模板ID，需要在短信应用中申请
        int templateId = sms.getTemplateId();
        // 签名，使用的是签名内容，而不是签名ID
        String smsSign = "小黑IT技术分享站";
        //随机生成四位验证码的工具类
        String code = KeyUtil.keyUtils();
        try {
            //参数，一定要对应短信模板中的参数顺序和个数，
            String[] params = {code, String.valueOf(min)};
            //创建ssender对象
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            //发送
            SmsSingleSenderResult result = ssender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");
            if (result.result == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("code", code);
                map.put("createTime", System.currentTimeMillis());
                JedisUtil.setJson(sms.getPhone(), JSONObject.toJSONString(map));
                reStr = "success";
            } else {
                reStr = "fail";
            }
            return reStr;
        }  // json解析错误
        // 网络IO错误
        catch (Exception e) {
            // HTTP响应码错误
            e.printStackTrace();
        }// 网络IO错误

        return reStr;
    }

    public static void checkSMS(SMS sms) {
        String code = sms.getCode();
        String o = JedisUtil.getJson(sms.getPhone());
        assert o != null;
        Map<String, Object> map = JSONObject.parseObject(o);
        String verifyCode = map.get("code").toString();
        long createTime = Long.parseLong(map.get("createTime").toString());
        if (!verifyCode.equals(code)) {
            throw new CustomUnauthorizedException("验证码错误(Code Error.)");
        }
//        if((System.currentTimeMillis() - createTime > 1000 * 60 * 3)){
//            throw new CustomUnauthorizedException("验证码过期(Code expire.)");
//        }
    }
}
